<template>
  <BasicLayout>
    <template #wrapper>
      <el-card class="box-card">
        <el-row :gutter="20">
          <el-form
            ref="queryForm"
            :model="queryParams"
            :inline="true"
            label-width="auto"
          >
            <!-- <el-form-item label="手机号:">
              <el-input
                v-model="queryParams.phone"
                placeholder="请输入手机号码"
                clearable
                size="small"
                style="width: 220px"
              />
            </el-form-item>
            <el-form-item label="用户状态:">
              <el-select
                v-model="queryParams.status"
                placeholder="请选择用户状态"
              >
                <el-option
                  v-for="item in statusSelect"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
            </el-form-item>
            <el-form-item label="所属门店:">
              <el-select
                v-model="queryParams.storeId"
                placeholder="请选择所属门店"
              >
                <el-option
                  v-for="item in allStores"
                  :key="item.storeId"
                  :label="item.storeName"
                  :value="item.storeId"
                >
                </el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="创建时间:">
              <el-date-picker
                v-model="dateValue"
                type="daterange"
                range-separator="至"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
                value-format="yyyy-MM-dd HH:mm:ss"
                :default-time="['00:00:00', '23:59:59']"
              >
              </el-date-picker>
            </el-form-item> -->

            <el-form-item class="right">
              <el-button size="mini" @click="reset">重置</el-button>
            </el-form-item>
            <el-form-item class="right">
              <el-button
                type="primary"
                icon="el-icon-search"
                size="mini"
                @click="getList"
              >查询</el-button>
            </el-form-item>
            <!-- <div>
              <el-form-item class="right">
                <el-button
                  type="primary"
                  icon="el-icon-plus"
                  size="mini"
                  @click="handleQuery"
                >添加用户</el-button>
              </el-form-item>
            </div> -->
          </el-form>

          <el-table v-loading="loading" :data="userList" border>
            <!-- <el-table-column
              type="index"
              width="50"
              label="序号"
              align="center"
            /> -->

            <el-table-column
              label="ID"
              align="center"
              prop="createdById"
              :show-overflow-tooltip="true"
            />
            <el-table-column
              label="手机号"
              align="center"
              prop="phone"
              :show-overflow-tooltip="true"
            />
            <el-table-column
              label="姓名"
              align="center"
              prop="userName"
              :show-overflow-tooltip="true"
            />
            <el-table-column
              label="角色"
              align="center"
              prop="userName"
              :show-overflow-tooltip="true"
            >
              超级管理员
            </el-table-column>
            <el-table-column
              label="状态"
              align="center"
              :show-overflow-tooltip="true"
            >
              <template slot-scope="scope">
                <span>{{ scope.row.userState == "ENABLE" ? "启用" : "禁用" }}</span>
              </template>
            </el-table-column>
            <!-- <el-table-column
              label="所属门店"
              align="center"
              prop="storeName"
              :show-overflow-tooltip="true"
            /> -->
            <el-table-column
              label="创建人"
              align="center"
              prop="createdByName"
              :show-overflow-tooltip="true"
            />
            <el-table-column
              label="创建时间"
              align="center"
              prop="createdTime"
              :show-overflow-tooltip="true"
            />
            <el-table-column
              label="最后修改人"
              align="center"
              prop="updatedByName"
              :show-overflow-tooltip="true"
            />
            <el-table-column
              label="最后修改时间"
              align="center"
              prop="updatedTime"
              :show-overflow-tooltip="true"
            />
            <el-table-column
              label="操作"
              align="center"
              width="250"
              class-name="small-padding fixed-width"
            >
              <!-- <template slot-scope="scope">

                <el-button
                  type="text"
                  @click="deleteUser(scope.row)"
                  v-if="scope.row.userState == 'ENABLE'"
                  >禁用</el-button
                >
                <el-button
                  type="text"
                  @click="startUser(scope.row.createdById)"
                  v-if="scope.row.userState == 'DISABLE'"
                  >启用</el-button
                >
                <el-button type="text" @click="getUserById(scope.row.createdById)"
                  >编辑</el-button
                >
              </template> -->
            </el-table-column>
          </el-table>

          <!-- 添加弹窗 -->
          <el-dialog title="添加用户" :visible.sync="dialogFormVisible">
            <el-form ref="addData" :model="addData" :rules="rules" status-icon>
              <el-form-item label="手机号：" label-width="120px" prop="phone">
                <el-input v-model="addData.phone" style="width: 75%" />
              </el-form-item>
              <el-form-item label="姓名：" label-width="120px" prop="userName">
                <el-input v-model="addData.userName" style="width: 75%" />
              </el-form-item>
              <el-form-item
                label="登录密码："
                label-width="120px"
                prop="password"
              >
                <el-input v-model="addData.password" style="width: 75%" />
              </el-form-item>
              <el-form-item
                label="确认密码："
                label-width="120px"
                prop="password2"
              >
                <el-input v-model="addData.password2" style="width: 75%" />
              </el-form-item>

              <el-form-item
                label="用户角色："
                label-width="120px"
                prop="roleId"
              >
                <el-select v-model="addData.roleId" placeholder="请选择角色">
                  <el-option
                    v-for="item in allRoles"
                    :key="item.id"
                    :label="item.roleName"
                    :value="item.id"
                  />
                </el-select>
              </el-form-item>
              <el-form-item
                label="所属门店："
                label-width="120px"
                prop="storeId"
              >
                <el-radio
                  v-model="addData.storeId"
                  :label="0"
                >所有店铺</el-radio>
                <el-radio
                  v-model="addData.storeId"
                  :label="1"
                >指定店铺</el-radio>
              </el-form-item>
            </el-form>
            <div slot="footer" class="dialog-footer">
              <el-button type="primary" @click="addRole">保 存</el-button>
              <el-button @click="dialogFormVisible = false">关 闭</el-button>
            </div>
          </el-dialog>

          <!-- 修改角色 -->
          <el-dialog title="修改用户" :visible.sync="dialogFormVisible2">
            <el-form
              ref="updateData"
              :model="updateData"
              :rules="rules2"
              status-icon
            >
              <el-form-item label="手机号：" label-width="120px" prop="phone">
                <el-input v-model="updateData.phone" style="width: 75%" />
              </el-form-item>
              <el-form-item label="姓名：" label-width="120px" prop="userName">
                <el-input v-model="updateData.userName" style="width: 75%" />
              </el-form-item>
              <el-form-item
                label="登录密码："
                label-width="120px"
                prop="password"
              >
                <el-input v-model="updateData.password" style="width: 75%" />
              </el-form-item>
              <el-form-item
                label="确认密码："
                label-width="120px"
                prop="password2"
              >
                <el-input v-model="updateData.password2" style="width: 75%" />
              </el-form-item>

              <el-form-item
                label="用户角色："
                label-width="120px"
                prop="roleId"
              >
                <el-select v-model="updateData.roleId" placeholder="请选择角色">
                  <el-option
                    v-for="item in allRoles"
                    :key="item.id"
                    :label="item.roleName"
                    :value="item.id"
                  />
                </el-select>
              </el-form-item>
              <el-form-item
                label="所属门店："
                label-width="120px"
                prop="storeId"
              >
                <el-radio
                  v-model="updateData.storeId"
                  :label="0"
                >所有店铺</el-radio>
                <el-radio
                  v-model="updateData.storeId"
                  :label="1"
                >指定店铺</el-radio>
              </el-form-item>
            </el-form>
            <div slot="footer" class="dialog-footer">
              <el-button type="primary" @click="updateUser">保 存</el-button>
              <el-button @click="dialogFormVisible2 = false">关 闭</el-button>
            </div>
          </el-dialog>

          <pagination
            v-show="total > 0"
            :total="total"
            :page.sync="queryParams.current"
            :limit.sync="queryParams.size"
            @pagination="getList"
          />
          <!-- </el-col> -->
        </el-row>
      </el-card>
    </template>
  </BasicLayout>
</template>

<script>
import {
  userList,
  updateStatus,
  add,
  getStoreMenu,
  initPassword,
  getUser,
  updateUser
} from '@/api/user-list';
import { getAllRoles } from '@/api/user-system';
// import { array } from 'js-md5';
import {
  validatePhone,
  validatePassword,
  validateName,
  validateIsNull
} from '@/utils/validate';
import md5 from 'js-md5';

export default {
  name: 'User',
  data() {
    const validatePasswordEqual = (rule, value, callback) => {
      if (this.addData.password !== this.addData.password2) {
        callback(new Error('两次密码输入不一致，请重新输入'));
      } else {
        callback();
      }
    };
    const validatePasswordEqua2 = (rule, value, callback) => {
      if (this.updateData.password !== this.updateData.password2) {
        callback(new Error('两次密码输入不一致，请重新输入'));
      } else {
        callback();
      }
    };
    return {
      rules: {
        phone: [{ required: true, trigger: 'blur', validator: validatePhone }],
        userName: [
          { required: true, trigger: 'blur', validator: validateName }
        ],
        password: [
          { required: true, trigger: 'blur', validator: validatePassword }
        ],
        password2: [
          { required: true, trigger: 'blur', validator: validatePassword },
          { required: true, trigger: 'blur', validator: validatePasswordEqual }
        ],
        roleId: [
          { required: true, trigger: 'blur', validator: validateIsNull }
        ]
      },
      rules2: {
        phone: [{ required: true, trigger: 'blur', validator: validatePhone }],
        userName: [
          { required: true, trigger: 'blur', validator: validateName }
        ],
        password: [
        ],
        password2: [
          { required: false, trigger: 'blur', validator: validatePasswordEqua2 }
        ],
        roleId: [
          { required: true, trigger: 'blur', validator: validateIsNull }
        ]
      },
      // 遮罩层
      loading: !true,
      // 总条数
      total: 0,
      // 用户表格数据
      userList: [],
      // 弹出层标题
      title: '',
      // 是否显示弹出层
      open: false,
      // 表单参数
      form: {},
      dialogFormVisible: false,
      dialogFormVisible2: false,
      dateValue: '',
      statusSelect: [
        {
          value: '',
          label: '全部'
        },
        {
          value: 0,
          label: '禁用'
        },
        {
          value: 1,
          label: '启用'
        }
      ],
      allRoles: [], // 全部角色
      allStores: [], // 全部店铺
      // 查询参数
      queryParams: {
        current: 1,
        size: 10
        // phone: '',
        // status: '',
        // storeId: '',
        // startTime: '',
        // endTime: ''
      },
      addData: {
        password: '',
        password2: '',
        phone: '',
        roleId: '',
        storeId: 0,
        userName: ''
      },
      updateData: {
        password: '',
        password2: '',
        phone: '',
        roleId: '',
        storeId: 0,
        userName: ''
      }
    };
  },
  watch: {},
  created() {
    this.getList();
    // this.getStoreMenu();
    // this.getAllRoles();
  },
  methods: {
    /** 查询列表 */
    getList() {
      this.loading = true;
      this.queryParams.startTime = this.dateValue[0];
      this.queryParams.endTime = this.dateValue[1];
      userList(this.queryParams).then((response) => {
        this.userList = response.data;
        this.total = response.total;
        this.loading = false;
      });
    },

    getAllRoles() {
      getAllRoles().then((res) => {
        this.allRoles = res.data;
      });
    },

    getStoreMenu() {
      getStoreMenu().then((res) => {
        this.allStores = res.data;
      });
    },

    /**
     * 重置
     */
    reset() {
      this.queryParams.current = 1;
      this.queryParams.phone = '';
      this.queryParams.status = '';
      this.queryParams.storeId = '';
      this.queryParams.startTime = '';
      this.queryParams.endTime = '';
      this.dateValue = '';

      this.getList();
    },

    /** 添加角色 */
    handleQuery() {
      this.addData = {
        password: '',
        password2: '',
        phone: '',
        roleId: '',
        storeId: 0,
        userName: ''
      };
      this.dialogFormVisible = true;
    },

    /** 修改,查询单个角色详情 */
    getUserById(userId) {
      getUser({ userId }).then((res) => {
        const uData = res.data;
        uData.password = '';
        uData.password2 = '';
        this.updateData = uData;
      });
      this.dialogFormVisible2 = true;
    },

    /**
     * 修改角色
     */
    updateUser() {
      this.$refs.updateData.validate((valid) => {
        if (!valid) return;
        const d = Object.assign({}, this.updateData);
        d.password = md5(d.password);
        d.password2 = md5(d.password);
        updateUser(d).then((res) => {
          this.getList();
          this.dialogFormVisible2 = false;
          this.$message({
            message: res.data,
            type: 'success'
          });
        });
      });
    },

    /** 添加角色 */
    addRole() {
      this.$refs.addData.validate((valid) => {
        if (!valid) return;
        const d = Object.assign({}, this.addData);
        d.password = md5(d.password);
        d.password2 = md5(d.password);

        add(d).then((res) => {
          this.getList();
          this.dialogFormVisible = false;
          this.$message({
            message: res.data,
            type: 'success'
          });
        });
      });
    },

    initAddData() {

    },

    /**
     * 禁用
     */
    deleteUser(data) {
      this.$alert(
        `禁用后${data.userName}将无法登录，确认禁用吗？`,
        '提示'
      ).then((res) => {
        this.updateStatus(data.id, 0);
      });
    },

    /**
     * 启用
     */
    startUser(userId) {
      this.$alert(`确定启用？`, '提示').then((res) => {
        this.updateStatus(userId, 1);
      });
    },

    /**
     * 初始化密码
     */
    updatePassword(data) {
      this.$alert(
        `确认将${data.userName}的登录密码初始化为123456？`,
        '提示'
      ).then((res) => {
        initPassword({ userId: data.id }).then((res) => {
          this.getList();
          this.$message({
            message: res.data,
            type: 'success'
          });
        });
      });
    },

    updateStatus(userId, status) {
      console.log(userId, status);
      updateStatus({ userId, status }).then((res) => {
        this.getList();
        this.$message({
          message: res.data,
          type: 'success'
        });
      });
    }
  }
};
</script>

<style lang="scss" scoped>
.createBut {
  margin-bottom: 20px;
}

.role_til {
  font-size: 15px;
  font-weight: 600;
  background-color: #eee;
  padding-left: 10px;
}

.role_item_til {
  border-bottom: 1px solid #eee;
}
</style>
